package io.mft.dev.base.config.builder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.bean.BeanUtil;
import io.mft.commons.config.ConfigProvider;
import io.mft.commons.exception.MFTException;
import io.mft.dev.base.ApiThreadExecutorConfig;
import io.mft.dev.base.config.builder.CatalogApiBuilder.CatalogApiCollection;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class ApiThreadExecutorConfigBuilder {
	private ClassLoader classLoader;
	
	public ApiThreadExecutorConfigBuilder(ClassLoader classLoader) {
		this.classLoader=classLoader;
	}
	
	public List<ApiThreadExecutorConfig> build() {
		List<ApiThreadExecutorConfig> apiThreadExecutorConfigs=new ArrayList<>();
		Map<String, ApiThreadExecutorConfig> container=new HashMap<String, ApiThreadExecutorConfig>();
		Map<String, Object> map=ConfigProvider.getConfigObject(classLoader,"apiThreadExecutor");
		if (map!=null) {
			map.keySet().forEach(systemKey->{
				Map<String, Object> moduleMap=ConfigProvider.getMapValue(map,systemKey);
				moduleMap.keySet().forEach(moduleKey->{
					try {
						Map<String, Object> kv=ConfigProvider.getMapValue(moduleMap,moduleKey);
						ApiThreadExecutorConfig config=BeanUtil.toBean(kv, ApiThreadExecutorConfig.class);
						config.setSystemKey(systemKey);
						config.setModuleKey(moduleKey);
						container.put(config.threadExecutorId(), config);
					} catch (MFTException e) {
						log.error("",e);
					}catch (Exception e) {
						log.error("应用插件["+classLoader.getResource(".").getPath()+"]系统["+systemKey+"]	模块["+moduleKey+"]apiThreadExecutor配置解析异常",e);
					}
				});
			});
		}
		CatalogApiBuilder catalogApiBuilder=new CatalogApiBuilder(classLoader);
		CatalogApiCollection catalogApiCollection=catalogApiBuilder.build();
		catalogApiCollection.getApiThreadExecutorConfigs().forEach(e->{
			container.put(e.threadExecutorId(), e);
		});
		apiThreadExecutorConfigs.addAll(container.values());
		return apiThreadExecutorConfigs;
	}
}
